import React from "react";
import styles from './index.less';
import { Modal, DatePicker, InputItem, Picker, Toast } from 'antd-mobile';
import ReactDOM from 'react-dom';
import QwcModal from '@/components/queryWbsCode';
import SeModal from '@/components/searchEmployee';
import { getMastId } from '@/utils/tools';
import UserServices from '@/services/user';
import { requestSuccess, addHidden, removeHidden } from '@/utils/tools';
// 请求后返回值

class addReimbursementInfoModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: true,
      isProjectCode: props.companyCode == '1100'?true:false,
      message: props.message,
      content: props.content,
      success: props.success,
      cancel: props.cancel,
      datepickerActiveKey: '',
      datepickerVisible: false,
      expenseItems: [],
      countrys: ['DOMESTIC','ABROAD'],
      provinces: {
        'DOMESTIC': ['China-First-tier city','China-Provincal capital','China-Other'],
        'ABROAD': ['America-America','Asia-Singapore','Asia-Japan','Asia-Korea','Asia-Taiwan','Asia-Others','Europe-others']
      },
      citys: {
        'China-First-tier city': ['Beijing 北京','Shanghai 上海','Guangzhou 广州','Shenzhen 深圳'],
        'China-Provincal capital': ['Wuhan 武汉','Changchun 长春','Changsha 长沙','Chengdu 成都','Chongqing 重庆','Fuzhou 福州','Guiyang 贵阳','Haikou 海口','Hangzhou 杭州','Harbin 哈尔滨','Hefei 合肥','Hohhot 呼和浩特','Jinan 济南','Kunming 昆明','Lanzhou 兰州','Lhasa 拉萨','Nanchang 南昌','Nanjing 南京','Shenyang 沈阳','Shijiazhuang 石家庄','Taiyuan 太原','Urumqi 乌鲁木齐','Xi’an 西安','Xining 西宁','Yinchuan 银川','Zhengzhou 郑州'],
        'China-Other': ['Other'],

        'America-America': ['New York','Sunnyvale','Chicago','Mountain View&Silicon Valley','Other'],
        'Asia-Singapore': ['Other'],
        'Asia-Japan': ['Other'],
        'Asia-Korea': ['Other'],
        'Asia-Taiwan': ['Other'],
        'Asia-Others': ['Other'],
        'Europe-others': ['Other'],
      },
      values: {
        companyCode: props.companyCode,
        expenseDetail: '',
        chargeEmployee: '',
        wbsCode: '',
        wbsManager: '',
        wbsName: '',
        country: '',
        province: '',
        city: '',
        expenseDateFrom: '',
        expenseDateTo: '',
        exchangeRateDate: '',
        claimAmt: '',
        currency: '',
        remark: ''
      }
    };
    window.cordovaBackEvents.push(() => {
      this.handleCancel();
    });
  }

  componentDidMount(){
    addHidden();
    // 获取 费用明细 与 币种的labels
    const id = getMastId(); //{traMastId: xx}
    const text = `${Object.keys(id)[0]}=${Object.values(id)[0]}`
    UserServices.getAddReimbursementInfoLabel(text).then(res => {
      if(requestSuccess(res)){
        const currencyList = this.state.isProjectCode
        ?
        res.data.currencyListX
        :
        res.data.currencyListY;
        const expenseItems = global._.map(res.data.expenseItems, item=>{
            return {
              label: item.itemName,
              value: item.itemName
            }
        })
        this.setState({
          expenseItems: expenseItems,
          currencyList: currencyList,
          projectCodeList: this.handleListLabel(res.data.projectCodeList)
        })
      }
    })
  }

  handleShowDatePicker = (activeKey) => {
    this.setState({
      datepickerActiveKey: activeKey,
      datepickerVisible: true
    })
  }

  handleFormatData = (data) => {
    const id = getMastId();

    return {
      ...id,
      orsItem:{
        ...data
      }
    }
  }

  handleSuccess = (e) => {
    const data = this.handleFormatData(this.state.values);

    const errorFn = (e) => {
      if(e){
        const message = e.message || 'Error';
        Toast.fail(message);
      }
    }
    UserServices.saveReimbursementInfo(data).then(res => {
      console.log(res);
      if(requestSuccess(res)){
        this.setState({
          visible: false,
        });
        removeHidden();
        // res.data.trsItem 为成功添加的那条
        this.state.success && this.state.success(res.data.mobileOrsItems);
      }else{
        const errorInfo = global._.get(res, 'data.errorMessageList');
        errorFn(new Error(errorInfo))
      }
    }).then(errorFn)

    // this.setState({
    //   visible: false,
    // });
    // this.state.success && this.state.success({...this.state.values});
  }

  handleCancel = (e) => {
    removeHidden();
    this.setState({
      visible: false,
    });
    this.state.cancel && this.state.cancel();
  }

  handleSaveDatepickerValue = (date) => {
    if(this.state.datepickerActiveKey){
      this.onChange(global.moment(date).format('YYYY-MM-DD').valueOf(), this.state.datepickerActiveKey);
      this.setState({
        datepickerVisible: false
      })
    }
  }

  onChange = (value, key) => {
    console.log(key);
    this.setState({
      values: {
        ...this.state.values,
        [key]: value
      }
    })
  }

  handleListLabel = (list) => {
    return global._.map(list, item => {
      return {
        label: item,
        value: item
      }
    });
  }

  handleSelectedEmployee = (key)=>{
    SeModal.open({
      success: (result) => {
        this.setState({values: {
          ...this.state.values,
          [key]: result.employees
        }})
      },
      cancel: () => {

      }
    })
  }

  handleChangeLocation = (type, value) => {
    if(type == 'country'){
      const activeProvince = this.state.provinces[value][0];
      const acitveCity = this.state.citys[activeProvince][0];
      this.setState({
        values: {
          ...this.state.values,
          country: value,
          province: activeProvince,//default
          city: acitveCity//default
        }
      })
    }else if(type == 'province'){
      this.setState({
        values: {
          ...this.state.values,
          province: value,
          city: this.state.citys[value][0]//default
        }
      })
    }else if(type == 'city'){
      this.setState({
        values: {
          ...this.state.values,
          city: value
        }
      })
    }
  }

  handleSelectedWbs = () => {
    QwcModal.open({
      success: (res) => {
        console.log(res);
        this.setState({
          values: {
            ...this.state.values,
            wbsCode: res.posid,
            wbsName: res.post1,
            wbsManager: res.xubname
          }
        })
      }
    })
  }

  render() {
    return (
      <Modal
        visible={this.state.visible}
        className={styles.addReimbursementInfoModal}
      >
      <div className={styles.modalWrapper}>
        <DatePicker
          visible={this.state.datepickerVisible}
          mode='date'
          value={this.state.datepickerValue}
          onOk={this.handleSaveDatepickerValue}
          onDismiss={() => this.setState({ datepickerVisible: false })}
        />
      <div className={styles.info}>Reimbursement Info Setting</div>
        <div className={styles.list}>
          <Picker data={this.state.expenseItems} cols={1} onChange={(values) => this.onChange(values[0], 'expenseDetail')}>
            <div className={styles.item}>
              <div className={styles.des}>*Expense Detail（费用明细）</div>
              <div className={styles.value}>{this.state.values.expenseDetail || 'Select'}</div>
            </div>
          </Picker>
          <div className={styles.item} onClick={() => this.handleSelectedEmployee('chargeEmployee')}>
            <div className={styles.des}>*Charge Employee（费用承担人）</div>
            <div className={styles.value}>{this.state.values.chargeEmployee || 'Select'}</div>
          </div>
          {
            this.state.isProjectCode
            ?
            <Picker data={this.state.projectCodeList} cols={1} onChange={(values) => this.onChange(values[0], 'wbsCode')}>
              <div className={styles.item}>
                <div className={styles.des}>Project Code</div>
                <div className={styles.value}>{this.state.values.wbsCode || 'Select'}</div>
              </div>
            </Picker>
            :
            <div className={styles.item} onClick={this.handleSelectedWbs}>
              <div className={styles.des}>WBS Code</div>
              <div className={styles.value}>{this.state.values.wbsName || 'Select'}</div>
            </div>
          }
          <Picker data={this.handleListLabel(this.state.countrys)} cols={1} onChange={(values) => this.handleChangeLocation('country', values[0])}>
            <div className={styles.item}>
              <div className={styles.des}>*Country（国家）</div>
              <div className={styles.value}>{this.state.values.country || 'Select'}</div>
            </div>
          </Picker>
          <Picker data={this.handleListLabel(this.state.provinces[this.state.values.country])} cols={1} onChange={(values) => this.handleChangeLocation('province', values[0])}>
            <div className={styles.item}>
              <div className={styles.des}>*Province（省份）</div>
              <div className={styles.value}>{this.state.values.province || 'Select'}</div>
            </div>
          </Picker>
          <Picker data={this.handleListLabel(this.state.citys[this.state.values.province])} cols={1} onChange={(values) => this.handleChangeLocation('city', values[0])}>
            <div className={styles.item}>
              <div className={styles.des}>*City（城市）</div>
              <div className={styles.value}>{this.state.values.city || 'Select'}</div>
            </div>
          </Picker>
          <div className={styles.item} onClick={() => this.handleShowDatePicker('expenseDateFrom')}>
            <div className={styles.des}>*Expense Date From（费用开始日）</div>
            <div className={styles.value}>{ this.state.values.expenseDateFrom || 'Select'}</div>
          </div>
          <div className={styles.item} onClick={() => this.handleShowDatePicker('expenseDateTo')}>
            <div className={styles.des}>*Expense Date To（费用截止日）</div>
            <div className={styles.value}>{ this.state.values.expenseDateTo || 'Select'}</div>
          </div>
          <div className={styles.item} onClick={() => this.handleShowDatePicker('exchangeRateDate')}>
            <div className={styles.des}>*Exchange Rate Date（汇率日期）</div>
            <div className={styles.value}>{this.state.values.exchangeRateDate || 'Select'}</div>
          </div>
          <div className={styles.item}>
            <div className={styles.des}>*Amount（金额）</div>
            <div className={styles.value}>
              <InputItem
                clear
                placeholder='click input'
                value={this.state.values.claimAmt}
                onChange={(value) => this.onChange(value, 'claimAmt')}
              ></InputItem>
            </div>
          </div>
          <Picker data={this.handleListLabel(this.state.currencyList)} cols={1} onChange={(values) => this.onChange(values[0], 'currency')}>
            <div className={styles.item}>
              <div className={styles.des}>*Currency（币种）</div>
              <div className={styles.value}>{this.state.values.currency || 'Select'}</div>
            </div>
          </Picker>
          <div className={styles.item}>
            <div className={styles.des}>*Remark（备注）</div>
            <div className={styles.value}>
              <InputItem
                clear
                placeholder="click input"
                value={this.state.values.remark}
                onChange={(value) => this.onChange(value, 'remark')}
              ></InputItem>
            </div>
          </div>
        </div>
        <div className={styles.footerBtns}>
          <div onClick={this.handleSuccess}>Save</div>
          <div onClick={this.handleCancel}>Cancel</div>
        </div>
      </div>
      </Modal>
    );
  }
}

export default {
  open(params){
    let div = document.createElement('div');
    document.body.appendChild(div);
    ReactDOM.render(React.createElement(addReimbursementInfoModal, params), div);
  }
};
